package com.briup.pts.service.impl;

import cn.hutool.core.util.StrUtil;
import com.briup.pts.entity.ManagerFenceHouse;
import com.briup.pts.entity.ManagerHurdles;
import com.briup.pts.entity.ManagerHurdlesExample;
import com.briup.pts.entity.extend.ManagerHurdlesExt;
import com.briup.pts.exception.ServiceException;
import com.briup.pts.mapper.ManagerFenceHouseMapper;
import com.briup.pts.mapper.ManagerHurdlesMapper;
import com.briup.pts.mapper.extend.ManagerHurdlesExtMapper;
import com.briup.pts.result.ResultCode;
import com.briup.pts.service.HurdlesService;
import com.briup.pts.utils.RandomStringGenerator;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;

@Service
public class HurdlesServiceImpl implements HurdlesService {
    @Autowired
    ManagerHurdlesMapper managerHurdlesMapper;
    @Autowired
    ManagerFenceHouseMapper managerFenceHouseMapper;
    @Autowired
    ManagerHurdlesExtMapper managerHurdlesExtMapper;

    @Override
    public List<Integer> findAllMax() {
        HashSet<Integer> set = new HashSet<>(managerHurdlesMapper.selectAllMax());
//        System.out.println("set = " + set);
        return new ArrayList<>(set);
    }

    @Override
    public List<ManagerFenceHouse> findAll() {
        return managerFenceHouseMapper.selectAll();
    }

    @Override
    public PageInfo<ManagerHurdlesExt> findByPage(Integer pageNum, Integer pageSize,
                                                  String hName, Integer hMax, String fhName, String hEnable) {
        PageHelper.startPage(pageNum,pageSize);

//        // 先按照条件查询所有的栏圈信息 -cgx
//        ManagerHurdlesExample managerHurdlesExample = new ManagerHurdlesExample();
//        ManagerHurdlesExample.Criteria criteria = managerHurdlesExample.createCriteria();
//        if (!StrUtil.isEmpty(hName)){
//            criteria = criteria.andHNameLike("%" + hName + "%");
//        }
//        if (hMax != null){
//            criteria = criteria.andHMaxEqualTo(hMax);
//        }
//        if (!StrUtil.isEmpty(fhName)){
//            // 如果栏舍名字不为空，那先需要查询栏舍的相关信息
//
//        }   // :( 只能使用编辑结果集

        // 自己写的
        List<ManagerHurdlesExt> managerHurdlesExts =
                managerHurdlesExtMapper.selectHurdlesAndFenceHouse(hName,hMax,fhName,hEnable);
        return new PageInfo<>(managerHurdlesExts);
    }

    @Transactional
    @Override
    public void saveOrUpdate(ManagerHurdles managerHurdles) {
        // 根据传入对象的hId区分新增和更新
        String hId = managerHurdles.getHId();
        if (StrUtil.isEmpty(hId)) {
            // 新增
            String newHId;
            ManagerHurdles existingHurdles;
            do {
                // 生成一个新的hId
                newHId = RandomStringGenerator.generateRandomString(32);
                // 检查新生成的fhId是否已存在
                existingHurdles = managerHurdlesMapper.selectByPrimaryKey(newHId);
            } while (existingHurdles != null); // 当hId已存在时，继续循环生成新的hId

            // 插入新的栏圈记录
            managerHurdles.setHId(newHId);
            managerHurdles.setHSaved(0);
            managerHurdles.setHFull("未满");
            int insertResult = managerHurdlesMapper.insert(managerHurdles);

            // 判断是否插入成功
            if (insertResult != 1) {
                throw new RuntimeException(ResultCode.FAIL + "Failed to insert new ManagerHurdles");
            }
        } else {
            // 更新
            int updateResult = managerHurdlesMapper.updateByPrimaryKeySelective(managerHurdles);

            // 判断是否更新成功（通常updateByPrimaryKeySelective返回影响的行数）
            if (updateResult != 1) {
                throw new ServiceException(ResultCode.FAIL + "Failed to update ManagerHurdles");
            }
        }
    }

    @Override
    public void modifyStatus(String hId, String hEnable) {
        // 直接使用三元运算符来切换状态
//        System.out.println("hEnable = " + hEnable);
        String newStatus = "启用".equals(hEnable) ? "禁用" : "启用";

        // 创建一个用于更新的ManagerHurdles对象，只设置需要更新的字段
        ManagerHurdles managerHurdles = new ManagerHurdles();
        managerHurdles.setHId(hId);
        managerHurdles.setHEnable(newStatus);
        managerHurdlesMapper.updateByPrimaryKeySelective(managerHurdles);
    }

    @Override
    public void modifyStatusBatch(List<Map<String, String>> idAndStatus) {
//        idAndStatus.forEach(System.out::println);
        idAndStatus.forEach((map)-> {
            modifyStatus(map.get("hId"),map.get("hEnable"));
        });
    }

    @Override
    public void removeById(String hId) {
        managerHurdlesMapper.deleteByPrimaryKey(hId);
    }

    @Override
    public void removeBatch(List<String> ids) {
        ManagerHurdlesExample managerHurdlesExample = new ManagerHurdlesExample();
        managerHurdlesExample.createCriteria().andHIdIn(ids);
        managerHurdlesMapper.deleteByExample(managerHurdlesExample);
    }

    @Override
    public List<ManagerHurdlesExt> findAllEnable() {
        ManagerHurdlesExample managerHurdlesExample = new ManagerHurdlesExample();
        managerHurdlesExample.createCriteria().andHEnableEqualTo("可用").andHFullEqualTo("未满");
        return managerHurdlesMapper.selectAllEnableHurdles();
    }

}
